package com.whj.wkpt.controller;

import com.whj.wkpt.entity.DeliveryAttachment;
import com.whj.wkpt.entity.Payment;
import com.whj.wkpt.entity.Task;
import com.whj.wkpt.entity.TaskApplication;
import com.whj.wkpt.entity.User;
import com.whj.wkpt.entity.TaskReview;
import com.whj.wkpt.service.DeliveryAttachmentService;
import com.whj.wkpt.service.PaymentService;
import com.whj.wkpt.service.TaskApplicationService;
import com.whj.wkpt.service.TaskService;
import com.whj.wkpt.service.UserService;
import com.whj.wkpt.service.TaskReviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/employer/task-applications")
public class EmployerTaskApplicationController {

    @Autowired
    private TaskApplicationService taskApplicationService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private UserService userService;
    
    @Autowired
    private PaymentService paymentService;
    
    @Autowired
    private DeliveryAttachmentService deliveryAttachmentService;
    
    @Autowired
    private TaskReviewService taskReviewService;
    
    @Value("${upload.path:uploads}")
    private String uploadPath;

    // 查看任务承接列表
    @GetMapping
    public String listTaskApplications(
            @RequestParam(required = false) Long taskId,
            @RequestParam(required = false) String status,
            Model model, 
            Authentication authentication) {
        
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(null);
        
        List<TaskApplication> applications = new ArrayList<>(); // 初始化为空列表
        Map<Long, Task> taskMap = new HashMap<>();
        Map<Long, User> freelancerMap = new HashMap<>();
        
        if (currentUser != null) {
            // 只获取当前雇主发布的任务的承接情况
            List<Task> employerTasks = taskService.findByEmployerId(currentUser.getUserId());
            List<Long> employerTaskIds = employerTasks.stream()
                    .map(Task::getTaskId)
                    .collect(Collectors.toList());
            
            // 如果指定了任务ID，检查该任务是否属于当前雇主
            if (taskId != null) {
                if (employerTaskIds.contains(taskId)) {
                    applications = taskApplicationService.searchApplications(taskId, status);
                } else {
                    // 如果任务不属于当前雇主，则返回空列表
                    applications = new ArrayList<>();
                }
            } else {
                // 获取所有雇主任务的承接情况
                if (!employerTaskIds.isEmpty()) {
                    applications = taskApplicationService.findByTaskIds(employerTaskIds);
                    
                    // 如果指定了状态，进行过滤
                    if (status != null && !status.isEmpty()) {
                        applications = applications.stream()
                                .filter(app -> status.equals(app.getDeliveryStatus()))
                                .collect(Collectors.toList());
                    }
                } else {
                    // 如果雇主没有发布任何任务，则返回空列表
                    applications = new ArrayList<>();
                }
            }
            
            // 获取任务标题信息
            if (!applications.isEmpty()) {
                List<Long> taskIds = applications.stream()
                        .map(TaskApplication::getTaskId)
                        .distinct()
                        .collect(Collectors.toList());
                
                List<Task> tasks = taskService.findByIds(taskIds);
                taskMap = tasks.stream()
                        .collect(Collectors.toMap(Task::getTaskId, task -> task));
                
                // 获取威客用户名信息
                List<Long> freelancerIds = applications.stream()
                        .map(TaskApplication::getFreelancerId)
                        .distinct()
                        .collect(Collectors.toList());
                
                if (!freelancerIds.isEmpty()) {
                    List<User> freelancers = userService.findByIds(freelancerIds);
                    freelancerMap = freelancers.stream()
                            .collect(Collectors.toMap(User::getUserId, user -> user));
                }
            }
        } else {
            // 如果用户未登录，返回空列表
            applications = new ArrayList<>();
        }
        
        model.addAttribute("applications", applications);
        model.addAttribute("taskMap", taskMap);
        model.addAttribute("freelancerMap", freelancerMap);
        model.addAttribute("searchTaskId", taskId);
        model.addAttribute("searchStatus", status);
        return "employer/task-application-list";
    }

    // 查看任务承接详情
    @GetMapping("/{applicationId}")
    public String viewTaskApplication(@PathVariable Long applicationId, Model model, Authentication authentication) {
        // 验证当前用户是否有权限查看此任务承接详情（即任务是否由该雇主发布）
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(null);
        
        if (currentUser != null) {
            TaskApplication application = taskApplicationService.findById(applicationId);
            
            // 检查该任务承接对应的任务是否由当前雇主发布
            if (application != null) {
                Task task = taskService.findById(application.getTaskId());
                if (task != null && task.getEmployerId().equals(currentUser.getUserId())) {
                    model.addAttribute("taskApplication", application);
                    
                    // 获取附件列表
                    List<DeliveryAttachment> attachments = deliveryAttachmentService.findByApplicationId(applicationId);
                    // 确保attachments不为null
                    if (attachments == null) {
                        attachments = new ArrayList<>();
                    }
                    model.addAttribute("attachments", attachments);
                    
                    // 获取评价列表
                    List<TaskReview> reviews = taskReviewService.findByTaskId(application.getTaskId());
                    model.addAttribute("reviews", reviews);
                    
                    return "employer/task-application-detail";
                }
            }
        }
        
        // 如果没有权限或找不到任务承接，重定向到列表页面
        return "redirect:/employer/task-applications";
    }

    // 更新任务承接状态 - 设置为已确认 (移除了标记为已交付的功能)
    @PostMapping("/{applicationId}/mark-confirmed")
    public String markAsConfirmed(@PathVariable Long applicationId) {
        TaskApplication application = taskApplicationService.findById(applicationId);
        if (application != null) {
            application.setDeliveryStatus("confirmed");
            taskApplicationService.updateApplication(application);
        }
        return "redirect:/employer/task-applications";
    }

    // 支付任务赏金
    @PostMapping("/{applicationId}/pay-bounty")
    public String payBounty(@PathVariable Long applicationId) {
        TaskApplication application = taskApplicationService.findById(applicationId);
        if (application != null) {
            Task task = taskService.findById(application.getTaskId());
            if (task != null) {
                // 检查任务承接状态是否为confirmed（已确认交付）
                if ("confirmed".equals(application.getDeliveryStatus())) {
                    // 重定向到支付宝支付页面，传递任务ID和任务承接ID
                    return "redirect:/alipay/pay?taskId=" + task.getTaskId() + "&applicationId=" + applicationId;
                }
            }
        }
        return "redirect:/employer/task-applications";
    }

    // 删除任务承接记录
    @PostMapping("/{applicationId}/delete")
    public String deleteTaskApplication(@PathVariable Long applicationId) {
        taskApplicationService.deleteApplication(applicationId);
        return "redirect:/employer/task-applications";
    }
    
    // 下载附件
    @GetMapping("/attachment/{attachmentId}")
    public ResponseEntity<Resource> downloadAttachment(@PathVariable Long attachmentId, Authentication authentication) {
        try {
            // 验证当前用户是否有权限下载此附件（即附件所属的任务是否由该雇主发布）
            String username = authentication.getName();
            User currentUser = userService.findByUsername(username).orElse(null);
            
            if (currentUser != null) {
                DeliveryAttachment attachment = deliveryAttachmentService.findById(attachmentId);
                if (attachment != null) {
                    // 获取附件所属的任务承接
                    TaskApplication application = taskApplicationService.findById(attachment.getApplicationId());
                    if (application != null) {
                        // 检查该任务承接对应的任务是否由当前雇主发布
                        Task task = taskService.findById(application.getTaskId());
                        if (task != null && task.getEmployerId().equals(currentUser.getUserId())) {
                            // 直接使用存储在数据库中的文件路径
                            Path filePath = Paths.get(attachment.getFilePath());
                            
                            // 检查文件是否存在
                            if (Files.exists(filePath)) {
                                Resource resource = new UrlResource(filePath.toUri());
                                
                                // 正确处理包含中文字符的文件名
                                String encodedFileName = URLEncoder.encode(attachment.getFileName(), StandardCharsets.UTF_8.toString())
                                        .replaceAll("\\+", "%20");
                                
                                return ResponseEntity.ok()
                                        .header(HttpHeaders.CONTENT_DISPOSITION, 
                                                "attachment; filename*=UTF-8''" + encodedFileName)
                                        .body(resource);
                            } else {
                                // 如果文件不存在，尝试在uploadPath目录下查找
                                String fileName = Paths.get(attachment.getFilePath()).getFileName().toString();
                                Path relativePath = Paths.get(uploadPath, fileName);
                                
                                // 如果uploadPath是相对路径，需要转换为绝对路径
                                if (!Paths.get(uploadPath).isAbsolute()) {
                                    relativePath = Paths.get(System.getProperty("user.dir"), uploadPath, fileName);
                                }
                                
                                if (Files.exists(relativePath)) {
                                    Resource resource = new UrlResource(relativePath.toUri());
                                    
                                    // 正确处理包含中文字符的文件名
                                    String encodedFileName = URLEncoder.encode(attachment.getFileName(), StandardCharsets.UTF_8.toString())
                                            .replaceAll("\\+", "%20");
                                    
                                    return ResponseEntity.ok()
                                            .header(HttpHeaders.CONTENT_DISPOSITION, 
                                                    "attachment; filename*=UTF-8''" + encodedFileName)
                                            .body(resource);
                                } else {
                                    System.out.println("File not found at both locations: " + filePath.toString() + " and " + relativePath.toString());
                                    System.out.println("Current working directory: " + System.getProperty("user.dir"));
                                    System.out.println("Upload path from config: " + uploadPath);
                                }
                            }
                        } else {
                            System.out.println("Task not found or not owned by current user. Task ID: " + 
                                (task != null ? task.getTaskId() : "null") + 
                                ", Employer ID: " + (task != null ? task.getEmployerId() : "null") + 
                                ", Current User ID: " + currentUser.getUserId());
                        }
                    } else {
                        System.out.println("Application not found for attachment. Application ID: " + attachment.getApplicationId());
                    }
                } else {
                    System.out.println("Attachment not found. Attachment ID: " + attachmentId);
                }
            } else {
                System.out.println("User not authenticated");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.notFound().build();
    }
}